/*
** 车险计费数据重构
** 将原数组结构，转为表格组件所需结构
*/
import { labelConf } from '@/components/ivew_conf/car_sy_plan'
import carPlanMap from '@/components/ivew_conf/car_plan_map'
import loop from '@/utils/loop'
import { deepCopy } from '@/utils/tools'


export default function chargingRestructrue (quotations:carOrder.Quotations[]){

    let newQuotations:formInf.carChargingListItem[] = [];
    
    // 反向重构列表项(构建模板)
    let template = loop.reverseBuild(carPlanMap, true);
    
    // 取值
    quotations.forEach((item, index) =>{

        let cache = loop.assignment(item, deepCopy(template), carPlanMap, true, transition);
        let jqCharging:formInf.carChargingItem[] = [];
        let syCharging:formInf.carChargingItem[] = [];
        let total = 0;
        let jqTotal = 0;
        let syTotal = 0;

        Object.keys(cache.jqCharging).forEach(key =>{
            
            // 计算交险合计
            if(key === 'jqTotal'){
                total += jqTotal = cache.jqCharging[key].discounted;
            }

            jqCharging.push({
                label: labelConf[key],
                key,
                discount: MathDiscount(cache.jqCharging[key]),
                ...cache.jqCharging[key]
            })

        })

        Object.keys(cache.syCharging).forEach(key =>{

            // 计算商险合计
            if(key === 'syTotal'){
                total += syTotal = cache.syCharging[key].discounted;
            }

            syCharging.push({
                label: labelConf[key],
                key,
                discount: MathDiscount(cache.syCharging[key]),
                ...cache.syCharging[key]
            })

        })
        
        newQuotations.push({
            jqCharging,
            syCharging,
            company: cache.company,
            tax:cache.tax,
            total: round(total),
            jqTotal,
            syTotal,
            index,
        })
        
    })
    
    return newQuotations;
}

function transition(val){
    
    // 取三位小数
    val = round(val);

    /* 交险负值，表示出现率    
    ** -0.1 一年为出险 
    ** -0.2 两年未出险
    ** -0.3 三年未出险
    */

    if(val < 0){
        val = ""
    }
    
    return val
}

// 格式化 取三位小数
function round(val){

    // NaN 跳出
    if(typeof val !== 'number'){
        return val;
    }

    return Math.round(val*1000)/1000;
}

function MathDiscount(val){
    let data =  round(val.discounted/val.orginnal)
    return isNaN(data) ? 0 : data;
}